<template>
  <div>
    <div class="tableTop1">
      <div class="top1Left">员工排班表</div>
      <div class="top1Right">
        <div class="day">
          <div style="cursor:pointer;margin-right:8px;" @click="dayPrev">
            <i class="el-icon-arrow-left"></i>
          </div>
          <div class="weekdate">
            {{ `${moment(expectDeliveryTime).format("YYYY年MM月DD日")}` }}
          </div>
          <div style="cursor:pointer;margin-left:8px;" @click="dayNext">
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
        <div style="cursor: pointer;color: #ff7f4c;margin-left:8px;" @click="goBackCurrent">
          回到今日
        </div>
      </div>
    </div>
    <div class="tableTop2">
      <span>用户期望服务时间: {{ expectDeliveryTime }}</span>
      <span>服务需要时长: {{ Math.ceil(serviceTotalTime).toFixed(2) }}小时</span>
      <span>服务人数:1</span>
    </div>
    <div class="tableTop3">
      <div style="display:flex;align-items: center;position:relative;">
        <div class="staffName" style="width:100px;">员工名称：</div>
        <el-input placeholder="搜索员工" v-model="searchStaffName"> </el-input>
        <i class="el-icon-search" @click="searchPeople"></i>
      </div>
      <div style="display:flex;align-items:center;">
        <div style="width:20px;height:20px;border: 1px solid #e5e5e5;border-radius:12px;margin-right:10px;background-color: #edf2fc;"></div>
        <div style="margin-right:10px;">不可约</div>
        <div style="width: 20px;height: 20px;border: 1px solid #E9E9E9;border-radius:50%;margin-right:5px;background-color: #ff8043;">
          <i class="el-icon-check" style="margin-left:3px;margin-top: 4px;"></i>
        </div>
        <div style="margin-right:10px;">已约</div>
        <div style="width:20px;height:20px;border: 1px solid #B1B1B1;border-radius:12px;margin-right:10px;"></div>
        <div>可约</div>
      </div>
    </div>
    <div class="tables" v-loading="lens !== '' ? false : true">
      <el-table :data="list" border ref="table" id="tableId" highlight-current-row @current-change="handleCurrentChangeDay" v-if="list.staffWorkTimeVos == [] ? '暂无数据' : list">
        <el-table-column prop="staffName" label="姓名/时间" width="80" v-if="list.length > 0">
          <template slot-scope="scope">
            {{ scope.row.staffName }}
          </template>
        </el-table-column>
        <el-table-column v-for="(item, index) in listtimes" prop="staffCode" :key="index" :label="item.time" width="60" class="fist">
          <template slot-scope="scope">
            <!-- 已约 -->
            <div v-if="scope.row.times[index].status == 1">
              <el-checkbox checked disabled class="one"></el-checkbox>
            </div>
            <!-- 不可约（包含请假和休息日） -->
            <div v-if="
                scope.row.times[index].status == 3 ||
                  scope.row.times[index].status == 2
              ">
              <el-checkbox disabled class="two"></el-checkbox>
            </div>
            <!-- 可约 -->
            <div v-if="scope.row.times[index].status == 4">
              <el-checkbox class="three" v-model="scope.row.times[index].checked" @change="
                  reducible(
                    scope.row.times[index],
                    $event,
                    scope.row.times[index].time,
                    scope.row.staffCode
                  )
                "></el-checkbox>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 派单 -->
    <el-dialog :visible.sync="centerDialogVisibles" width="30%" center :modal="false" @close="sandersDialog">
      <span>当前选择时段：{{ fisttims }}</span>
      <div style="margin-top:10px;">
        <span style="margin-right:40px;">服务人数：1</span>
        <span>服务总时长:{{ Math.ceil(serviceTotalTime).toFixed(2) }}小时</span>
      </div>
      <p style="margin-top:10px;">是否确认派单？</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sanders">重新选择</el-button>
        <el-button style="background-color:#fd804c;color: #fff;" @click="sander">立即派单</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
export default {
  name: "Manually",
  props: ["serviceStartTime", "workOrderNos", 'orderItemType'],
  data () {
    var _this = this
    return {
      nums: [],
      list: [],
      value: [],
      states: [],
      getChangetime: [],
      changgetimes: '',
      checkboxGroup: [],
      startTime: "",
      changgetimas: '',
      endTime: "",
      listtimes: "",
      fisttims: "",
      changetime: "",
      times: "",
      back: "",
      loading: "",
      lens: "",
      staffCodes: "",
      orderType: '',
      searchStaffName: "",
      serviceTotalTime: "",
      expectDeliveryTime: "",
      currentRowDay: null,
      centerDialogVisibles: false,
      //选择时间
      expireTimeOption: {
        disabledDate (time) {
          let times = _this.changgetimes
          let curDate = new Date().getTime(); //  获取当前时间点
          let seven = times * 24 * 60 * 60 * 1000; // 设定7天日期  7天 * 24小时 * 60分钟 * 60秒 * 1000 = 7天的时间戳
          let sevenDays = curDate + seven; //  当前时间点后的七天所处的日期
          return (
            time.getTime() < Date.now() - 8.64e7 ||
            time.getTime() > sevenDays - 8.64e7
          );
        }
      },
    };
  },
  created () {
    this.getList();
    this.dataList();
    this.expectDeliveryTime = this.serviceStartTime;
  },
  methods: {
    //接口
    getList () {
      this.$http({
        url:
          "/staffadmin/homeService/staffWorkOrder/getManualDispatcherWorkOrderList",
        params: {
          workOrderNo: this.workOrderNos,
          date: moment(this.serviceStartTime).format("YYYY-MM-DD")
        }
      }).then(res => {
        console.log(res.data, "手动派单");
        this.lens = res.data.staffWorkTimeVos.length;
        if (this.lens > 0) {
          this.list = res.data.staffWorkTimeVos;
          this.serviceTotalTime = (
            res.data.simpleWordOrder.serviceTotalTime / 60
          ).toFixed(2);
          res.data.staffWorkTimeVos.forEach(e => {
            e.times.forEach(k => {
              k.checked === true;
            });
            this.listtimes = e.times;
          });
        } else {
          this.$message.error("没有可派单的阿姨!");
        }
      });
    },
    //回到今日
    goBackCurrent () {
      this.list = [];
      let data = moment(new Date()).format("YYYY-MM-DD"); //当前日期
      this.expectDeliveryTime = data;
      this.$http({
        url:
          "/staffadmin/homeService/staffWorkOrder/getManualDispatcherWorkOrderList",
        params: {
          workOrderNo: this.workOrderNos,
          date: this.expectDeliveryTime
        }
      }).then(res => {
        this.lens = res.data.staffWorkTimeVos.length
        if (res.data.staffWorkTimeVos.length > 0) {
          this.list = res.data.staffWorkTimeVos;
          res.data.staffWorkTimeVos.forEach(e => {
            e.times.forEach(k => {
              k.checked === true;
            });
            this.listtimes = e.times;
          });
        } else {
          this.$message.error('没有可派单的阿姨!');
        }
        //console.log(res, "回到今日");
      });
    },
    //减一天
    dayPrev () {
      this.list = [];
      const dayPrev = moment(new Date(this.expectDeliveryTime))
        .subtract(1, "days")
        .format("YYYY-MM-DD");
      this.expectDeliveryTime = dayPrev;
      this.$http({
        url:
          "/staffadmin/homeService/staffWorkOrder/getManualDispatcherWorkOrderList",
        params: {
          workOrderNo: this.workOrderNos,
          date: this.expectDeliveryTime
        }
      }).then(res => {
        this.lens = res.data.staffWorkTimeVos.length
        if (res.data.staffWorkTimeVos.length > 0) {
          this.list = res.data.staffWorkTimeVos;
          res.data.staffWorkTimeVos.forEach(e => {
            e.times.forEach(k => {
              k.checked === true;
            });
            this.listtimes = e.times;
          });
        } else {
          this.$message.error('没有可派单的阿姨!');
        }
        //console.log(res, "减一天");
      });
    },
    //加一天
    dayNext () {
      this.list = [];
      const dayNext = moment(new Date(this.expectDeliveryTime))
        .add(1, "days")
        .format("YYYY-MM-DD");
      this.expectDeliveryTime = dayNext;
      this.$http({
        url:
          "/staffadmin/homeService/staffWorkOrder/getManualDispatcherWorkOrderList",
        params: {
          workOrderNo: this.workOrderNos,
          date: this.expectDeliveryTime
        }
      }).then(res => {
        this.lens = res.data.staffWorkTimeVos.length
        if (res.data.staffWorkTimeVos.length > 0) {
          this.list = res.data.staffWorkTimeVos;
          res.data.staffWorkTimeVos.forEach(e => {
            e.times.forEach(k => {
              k.checked === true;
            });
            this.listtimes = e.times;
          });
        } else {
          this.$message.error('没有可派单的阿姨!');
        }
        //console.log(res, "加一天");
      });
    },
    //改约日历范围
    dataList () {
      this.$http({
        url:
          "/staffadmin/homeService/staffWorkOrder/getChangeAboutCalendarScope",
        method: "get",
        params: {
          workOrderNo: this.workOrderNos
        }
      }).then(res => {
        console.log(res.data, "改约日历范围");
        this.getChangetime = res.data
        this.changgetimes = res.data.length;
      });
    },
    //选择时间
    changestarttime (e) {
      this.changgetimas = e
      let times = this.getChangetime.filter(item => { return item.date === this.changgetimas })
      let arr = times[0] && times[0].timeLine
      let arr1 = arr && arr.split('-')
      let time1 = arr1 && arr1.shift()
      let time2 = arr1 && arr1.pop()

      this.list = [];
      this.$http({
        url:
          "/staffadmin/homeService/staffWorkOrder/getManualDispatcherWorkOrderList",
        params: {
          workOrderNo: this.workOrderNos,
          date: e || moment(this.serviceStartTime).format("YYYY-MM-DD")
        }
      }).then(res => {
        this.lens = res.data.staffWorkTimeVos.length;
        if (res.data.staffWorkTimeVos.length > 0) {
          this.list = res.data.staffWorkTimeVos;
          this.serviceTotalTime = (
            res.data.simpleWordOrder.serviceTotalTime / 60
          ).toFixed(2);
          if (e === null) {
            res.data.staffWorkTimeVos.forEach(e => {
              e.times.forEach(k => {
                k.checked === true;
              });
              this.listtimes = e.times;
            });
          } else {
            res.data.staffWorkTimeVos.forEach(e => {
              const index1 = e.times.findIndex(item => item.time === time1)
              const index2 = e.times.findIndex(item => item.time === time2)
              const index3 = e.times.slice(index1, index2 + 1)
              this.listtimes = index3;
            });
          }
        } else {
          this.$message.error("没有可派单的阿姨!");
        }
      });
    },
    // 立即派单
    sander () {
      const data = {
        serviceStartTime: this.startTime,
        serviceEndTime: this.endTime,
        staffCode: this.staffCodes,
        workOrderNo: this.workOrderNos
      };
      this.$http({
        url: "/hssorderadmin/order/memOrder/manualDispatcherWorkOrder",
        method: "POST",
        data
      }).then(res => {
        //console.log(res, "立即派单");
        this.$message({
          message: "派单成功",
          type: "success"
        });
        this.centerDialogVisibles = false;
        location.reload();
      });
    },
    //重新选择
    sanders () {
      this.centerDialogVisibles = false;
      this.states.forEach(e => (e.checked = false));
      this.value = [];
      this.states = [];
      this.nums = [];
    },
    //关闭弹框的事件
    sandersDialog () {
      this.centerDialogVisibles = false;
      this.states.forEach(e => (e.checked = false));
      this.value = [];
      this.states = [];
      this.nums = [];
    },
    //可约
    reducible (j, s, time, e) {
      this.states.push(j);
      if (s) {
        this.nums.push(time);
      } else {
        this.nums.splice(this.nums.indexOf(time), 1);
      }

      //时间选择不能有间隔
      let arr = this.nums;
      let dates = Array.from(new Set(arr));
      let arraySort = this.arrSort(dates);
      for (let i = 0; i < arraySort.length; i++) {
        if (i > 0) {
          let beforeDate = new Date(
            "2021",
            "09",
            "30",
            arraySort[i - 1].split(":")[0],
            arraySort[i - 1].split(":")[1],
            "00"
          );
          let afterDate = new Date(
            "2021",
            "09",
            "30",
            arraySort[i].split(":")[0],
            arraySort[i].split(":")[1],
            "00"
          );
          let min = beforeDate.getMinutes();
          beforeDate.setMinutes(min + 30);
          if (beforeDate.getTime() != afterDate.getTime()) {
            this.$message.error("时间选择不能有间隔！");
            this.states.forEach(e => (e.checked = false));
            this.value = [];
            this.states = [];
            this.nums = [];
          }
        }
      }

      // 派单传值
      let el = this.nums[this.nums.length - 1]; //最后
      let ell = this.nums[0]; //最新
      let day = moment(this.expectDeliveryTime).format("YYYY-MM-DD");
      this.startTime = `${day} ${ell}:00`;
      this.endTime = `${day} ${el}:00`;
      this.fisttims = `${day} ${ell} ~ ${el}`;
      this.staffCodes = e;

      //派单弹框
      if (this.serviceTotalTime == 0.00) {
        this.$message.error("没有可派单的阿姨!")
        this.states.forEach(e => (e.checked = false));
        this.states = [];
        this.nums = [];
      } else {
        if (
          Array.from(new Set(this.nums)).length ===
          Math.ceil(this.serviceTotalTime) * 2 + 1
        ) {
          this.centerDialogVisibles = true;
        }
      }
      // 阿姨code不能重复
      this.value.push(e);
      let a = this.value[0]; //最新
      let all = this.value[this.value.length - 1]; //最后
      if (a !== all) {
        this.$message.error("错了哦，请选择一位阿姨");
        this.states.forEach(e => (e.checked = false));
        this.value = [];
        this.states = [];
      }
    },
    arrSort (arr) {
      let len = arr.length;
      for (let i = 0; i < len - 1; i++) {
        for (let j = 0; j < len - 1 - i; j++) {
          let beforeDate = new Date(
            "2021",
            "09",
            "30",
            arr[j].split(":")[0],
            arr[j].split(":")[1],
            "00"
          );
          let afterDate = new Date(
            "2021",
            "09",
            "30",
            arr[j + 1].split(":")[0],
            arr[j + 1].split(":")[1],
            "00"
          );
          if (beforeDate.getTime() > afterDate.getTime()) {
            let temp = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = temp;
          }
        }
      }
      return arr;
    },
    //搜索员工
    setCurrent (row) {
      this.$refs.table.setCurrentRow(row);
    },
    handleCurrentChangeDay (value) {
      this.currentRowDay = value;
    },
    searchPeople () {
      if (this.searchStaffName === "") {
        this.$message.error("请输入员工姓名");
        return false;
      }
      let refTab = this.$refs.table;
      let refdata = refTab.data;
      // //console.log(refTab)
      for (let i = 0; i < refdata.length; i++) {
        if (refdata[i].hasOwnProperty("staffName")) {
          var tableIdLocation = refdata
            .map(item => item.staffName)
            .indexOf(this.searchStaffName);
        }
      }
      // //console.log(tableIdLocation)
      if (tableIdLocation == -1) {
        this.$message.error("查询不到此员工");
        return false;
      }
      this.setCurrent(refdata[tableIdLocation]);
      let myTableId = document.getElementById("tableId").childNodes;
      let myTableIdChildNo3 = myTableId[2].childNodes;
      // //console.log(myTableIdChildNo3)
      let myTableIdChildNo3ChildNo1 = myTableIdChildNo3[0].childNodes;
      let tbobyChildNo2 = myTableIdChildNo3ChildNo1[1];
      let kk = tbobyChildNo2.childNodes;
      let kkll = kk[tableIdLocation];
      kkll.setAttribute("id", "table_td_bg");
      let element = document.getElementById("table_td_bg");
      element.scrollIntoView({ block: "center" });
    }
  }
};
</script>

<style lang="scss" scoped>
.tableTop1 {
  display: flex;
  justify-content: space-between;
  padding-right: 40px;
  .day {
    display: flex;
  }
  .top1Right {
    display: flex;
  }
}

.tableTop2 {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
  padding: 0 32px 0 32px;
  height: 45px;
  line-height: 45px;
}

.tableTop3 {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.tables {
  margin-top: 10px;
  /deep/ .el-table__row {
    cursor: pointer;
    line-height: 0px;
    font-size: 12px;
    font-weight: 400;
  }
}

/deep/ .el-icon-check:before {
  color: #fff;
}

/deep/ .el-checkbox__inner {
  width: 20px;
  height: 20px;
  border-radius: 10px;
}

/deep/ .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
  top: 3px;
  left: 6px;
  width: 5px;
  height: 8px;
  border-color: #fff;
}

.one {
  /deep/ .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
    background-color: #ff8043;
    border-radius: 10px;
  }
}

.three {
  /deep/ .el-checkbox__input.is-focus .el-checkbox__inner {
    border-color: #b1b1b1;
  }

  /deep/ .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #fff;
    border: 1px solid #b1b1b1;
  }

  /deep/ .el-checkbox__inner::after {
    top: 3px;
    left: 6px;
    width: 5px;
    height: 8px;
    border-color: #b1b1b1;
  }
}

.el-icon-search {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
}

/deep/ .has-gutter {
  font-size: 13px;
}
</style>
